import { computed, onMounted, onUnmounted, ref, type Ref } from "vue";
import { filter, type ITodo } from "../utils/todoStorage";

const validHash = ["all", "active", "completed"];
export default function useFilter(todosRef: Ref<ITodo[]>) {
  const visibilityRef = ref("all");

  const onHashchange = () => {
    const hash = window.location.hash.replace(/#\/?/, "");
    if (validHash.includes(hash)) {
      visibilityRef.value = hash;
    } else {
      window.location.hash = "";
      visibilityRef.value = "all";
    }
  };

  const filteredTodoRef = computed(() => {
    return filter(todosRef.value, visibilityRef.value);
  });

  const remainingRef = computed(() => {
    return filter(todosRef.value, "active").length;
  });

  const completedRef = computed(() => {
    return filter(todosRef.value, "completed").length;
  });

  onMounted(() => {
    window.addEventListener("hashchange", onHashchange);
  });

  onUnmounted(() => {
    window.removeEventListener("hashchange", onHashchange);
  });

  return {
    visibilityRef,
    filteredTodoRef,
    remainingRef,
    completedRef,
  };
}
